package com.chunxuan.langquan.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.Banner;
import com.chunxuan.langquan.dao.bean.CourseBean;
import com.chunxuan.langquan.dao.bean.Subject;
import com.chunxuan.langquan.dao.bean.SubjectBean;
import com.chunxuan.langquan.dao.bean.SubjectBean1;
import com.chunxuan.langquan.dao.bean.SubjectBean2;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.dao.http.APIRetrofit2;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.ui.adapter.SubjectAdapter;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class SubjectActivity extends Base2Activity implements HandlerUtil.OnReceiveMessageListener {
    private RecyclerView rvSubject;
    private SubjectBean2 subjectBean2;
    private ImageView ivBack;
    private List<SubjectBean1> subjectBean1List = new ArrayList<>();

    private ViewPager vp;

    private RelativeLayout rl_search;// 精选文章,报告解读,下单,搜索
    private ImageView iv_notice;// 消息, 返回
    private TextView vUnreadCount;
    private List<CourseBean> courseBeanList = new ArrayList<>();
    private RecyclerView rvCourse;
    private List<SubjectBean> subjectBeanList = new ArrayList<>();

    private List<Banner> bannerList = new ArrayList<>();// banner的数据
    private VpAdapter adapter;// banner

    private int currIndex = 0;
    private HandlerUtil.HandlerHolder handler;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_course_main;
    }
    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 21031052) {// 轮播
            handler.removeMessages(21031052);
            try {
                currIndex++;
                if (currIndex >= bannerList.size()) {
                    currIndex = 0;
                }
                vp.setCurrentItem(currIndex, true);
                handler.sendEmptyMessageDelayed(21031052, 5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rvSubject = findViewById(R.id.rlv);
        ivBack=findViewById(R.id.iv_back);

        iv_notice = findViewById(R.id.iv_shopping_market_cart);
        rl_search = findViewById(R.id.rl_search);
        vUnreadCount = findViewById(R.id.vUnreadCount);
        vp = findViewById(R.id.vp);

        adapter = new VpAdapter();
        vp.setAdapter(adapter);


        Intent intent = getIntent();
        if (null != intent) {
            int subject_category_id = intent.getIntExtra("subject_category_id", 0);
            getSubject(subject_category_id);
        }
        setListeners();

        reqBannerList();// 请求banner列表
        setOnClickListener(ivBack);
        handler = new HandlerUtil.HandlerHolder(this);
    }
    private void setListeners() {
        setOnClickListener(iv_notice, rl_search);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
    // 请求首页banner
    private Disposable reqBannerList() {
        return APIRetrofit2.getDefault().reqBannerList(Global.HEADER, 2)
                .compose(RxUtil.<BaseResult2<List<Banner>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Banner>>>() {
                    @Override
                    public void accept(BaseResult2<List<Banner>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        bannerList = listBaseResult2.getData();
                        adapter.notifyDataSetChanged();

                        handler.sendEmptyMessageDelayed(21031052, 5000);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }
    // banner adapter
    private class VpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView iv = new ImageView(SubjectActivity.this);
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

//            iv.setImageResource(R.drawable.home_top_banner);
            GlideUtil.loadImg(bannerList.get(position).getAd_image(), iv);

            container.addView(iv);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(bannerList.get(position).getAd_url())){
                        Intent intent=new Intent(SubjectActivity.this, WebViewActivity.class);
                        intent.putExtra("ad_url",bannerList.get(position).getAd_url());
                        startActivity(intent);
                    }
                }
            });
            return iv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_search:// 搜索
                startActivity(SearchCourseActivity.class);
                break;
            case R.id.iv_shopping_market_cart:// 消息
//            startActivityForResult(new Intent(getActivity(), MsgListActivity.class), 1001);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private Disposable getSubject(final int subject_category_id) {
        return APIRetrofit.getDefault().subjectPage(Global.HEADER, subject_category_id)
                .compose(RxUtil.<BaseResult2<List<Subject>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Subject>>>() {
                    @Override
                    public void accept(BaseResult2<List<Subject>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<Subject> subjectList = result2.getData();
                            if (!isDataEmpty(subjectList)) {
//                                Logg.e("==科目页==" + subjectList.get(0).getList().getData().get(0).getContent());
                                GridLayoutManager gridLayoutManager = new GridLayoutManager(SubjectActivity.this, 2);
                                rvSubject.setLayoutManager(gridLayoutManager);
                                for (int m = 0; m < subjectList.size(); m++) {
                                    if (subjectList.get(m).getList().getData().size() > 0) {
                                        for (int w = 0; w < subjectList.get(m).getList().getData().size(); w++) {
                                            subjectBean1List.add(subjectList.get(m).getList().getData().get(w));
                                        }
                                    }
                                }
                                SubjectAdapter subjectAdapter = new SubjectAdapter(SubjectActivity.this, subjectBean1List);
                                int index = 0;
                                for (int t = 0; t < subjectList.size(); t++) {
                                    SubjectBean2 subjectBean2 = new SubjectBean2();
                                    subjectBean2.setSubject_category_id(subject_category_id);
                                    subjectBean2.setClass_category_id(subjectList.get(t).getSubject_category_id());
                                    subjectBean2.setName(subjectList.get(t).getName());
                                    if (t == 0) {
                                        index = t;
                                        subjectAdapter.addTitle(0, subjectBean2);
                                    } else {
                                        index += subjectList.get(t - 1).getList().getData().size() + 1;
                                        subjectAdapter.addTitle(index, subjectBean2);
                                    }
                                }
                                rvSubject.setAdapter(subjectAdapter);
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取科目列表失败");
                    }
                });
    }
}